package com.googlecode.garbagecan.commons.execstudy;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;

public class Sample4 {
	
	private static Logger logger = Logger.getLogger(Sample4.class.getName());
	
	public static void main(String[] args) {
		test();
	}

	public static void test() {
		CommandLine cmdLine = new CommandLine("sleep");
		cmdLine.addArgument("5");
		
		DefaultExecutor executor = new DefaultExecutor();
		ExecuteWatchdog watchdog = new ExecuteWatchdog(2 * 1000);
		executor.setWatchdog(watchdog);
		
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		
		try {
			executor.execute(cmdLine, resultHandler);
		} catch (ExecuteException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		} catch (IOException e) {
			logger.log(Level.SEVERE, e.getMessage(), e);
		}
		
		try {
			resultHandler.waitFor(10 * 1000);
		} catch (InterruptedException ex) {
			logger.log(Level.SEVERE, null, ex);
		}
		
		logger.log(Level.INFO, "Has result: " + resultHandler.hasResult());
		if (resultHandler.hasResult()) {
			logger.log(Level.INFO, "Exit value: " + resultHandler.getExitValue());
			logger.log(Level.INFO, "Exception: " + resultHandler.getException());
		}
	}
}
